#include "texturepreviewlabel.h"
#include "resourceloader.h"
#include <QPainter>

namespace PublicGui
{
	TexturePreviewLabel::TexturePreviewLabel(QWidget* parent): QLabel(parent)
		, _image(NULL)
	{}

	void TexturePreviewLabel::setTextureFile(const QString& texturefile)
	{
		_imageFileName = texturefile;
		_image = CoreBase::ResourceLoader::GetInstance().getImageByFileName(texturefile);
		repaint();
	}

	void TexturePreviewLabel::setImage(osg::ref_ptr<osg::Image> image)
	{
		_imageFileName = "";
		_image = image;
		repaint();
	}

	QString TexturePreviewLabel::getTextureFile()
	{
		if (_image.valid())
		{
			return _imageFileName;
		}
		else
		{
			return "";
		}
	}

	void TexturePreviewLabel::paintEvent(QPaintEvent* event)
	{
		QImage qimage = QImage(width(), height(), QImage::Format_ARGB32);
		qimage.fill(qRgb(255, 255, 255));
		QPainter painter(this);
		if(_image.valid())
		{
			int w = std::max(_image->s(), width());
			int h = std::max(_image->t(), height());
			qimage = QImage(w, h, QImage::Format_ARGB32);
			drawLoadedImage(qimage);
		}
		painter.drawImage(QPoint(0, 0), qimage);
	}

	void TexturePreviewLabel::drawLoadedImage(QImage& image)
	{
		float sstep = (float)_image->s() / width();
		float tstep = (float)_image->t() / height();
		float s = 0.0f;
		float t = _image->t() - tstep;
		int components = osg::Image::computeNumComponents(_image->getPixelFormat());
		for(int x = 0; x < image.width() && s < _image->s(); ++x)
		{
			t = _image->t() - tstep;
			for(int y = 0; y < image.height() && t >= 0; ++y)
			{
				uchar* data = _image->data((int)s, (int)t);
				QColor pixelColor;
				switch(components)
				{
				case 1:
					pixelColor.setRgb((int)data[0], (int)data[0], (int)data[0]);
					break;
				case 3:
					pixelColor.setRgb((int)data[0], (int)data[1], (int)data[2]);
					break;
				case 4:
					float alpha = data[3] / 255.0f;
					pixelColor.setRgb((int)data[0] * alpha, (int)data[1] * alpha, (int)data[2] * alpha);
					break;
				}
				image.setPixel(x, y, pixelColor.rgba());
				t -= tstep;
			}
			s += sstep;
		}
	}
}